package wc.frequency;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import wc.fileUtil.FileCollector;
import wc.fileUtil.FileReader;
import wc.fileUtil.exception.NoReadableFileException;
import wc.parserUtil.ParserWords;

public class Frequency {

	private HashMap<String, Integer> _words = new HashMap<String, Integer>();
	
	public Frequency(FileCollector fileCollector, FileReader fileReader, ParserWords parser) {
		for(File f : fileCollector.getFiles()) {
			try {
				fileReader.parseFile(f);
			} catch (NoReadableFileException e) {
				e.printStackTrace();
			}
			for(String line : fileReader.getFileContent()) {
				parser.parseLine(line, true);
				for(String word : parser.getItems()) {
					if(_words.containsKey(word)) {
						int freq = _words.get(word);
						_words.put(word, freq + 1);
					} else {
						_words.put(word, 1);
					}
				}
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Map.Entry<String, Float>> getFrequency() {
		Map<String, Float> freq = new HashMap<String, Float>();
        float count = _words.size();
        for(String key : _words.keySet()) {
            freq.put(key, (float) _words.get(key) / count);
        }

        List<Map.Entry<String, Float>> frequency = new ArrayList<Map.Entry<String, Float>>(freq.entrySet());
        Collections.sort(frequency, new Comparator<Object>() {
            public int compare(Object o, Object o1) {
				Map.Entry<String, Float> e1 = (Map.Entry<String, Float>)o;
                Map.Entry<String, Float> e2 = (Map.Entry<String, Float>)o1;
                Float first = (Float)e1.getValue();
                Float second = (Float)e2.getValue();
                return -first.compareTo(second);
            }
        });
		return frequency;
	}
	
}
